package com.innovation.sys.common.utils;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.innovation.sys.pojo.SSysAccount;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtUtils {

    // 过期时间 5分钟
    private static final long EXPIRE_TIME = 5 * 60 * 1000;

    public static String createJWT(Map<String,Object> claims) {
        //指定签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //生成JWT的时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        //密钥
        String key = (String) claims.get("password");
        //生成签发人
        String subject = (String) claims.get("username");
        //构建JWT BODY
        JwtBuilder builder = Jwts.builder()
                //如果有私有声明，则需要在此声明
                .setClaims(claims)
                //JWTID,JWT的唯一标识
                .setId(UUID.randomUUID().toString())
                //JWT签发时间
                .setIssuedAt(now)
                //JWT主体，作为用户的唯一标识。
                .setSubject(subject)
                //签名算法及秘钥
                .signWith(signatureAlgorithm, key);
        if (EXPIRE_TIME >= 0) {
            long expMillis = nowMillis + EXPIRE_TIME;
            Date exp = new Date(expMillis);
            //设置过期时间
            builder.setExpiration(exp);
        }
        return builder.compact();
    }
    
    //解密JWT
    public static Claims parseJWT(String token,SSysAccount account) {
        //签名秘钥
        String key = account.getPassword();
        Claims claims = Jwts.parser()
                //设置签名秘钥
                .setSigningKey(key)
                //设置解析JWT
                .parseClaimsJws(token).getBody();
        return claims;
    }

    //检验TOKEN
    public static Boolean isVerify(String token,SSysAccount account) {
        //签名秘钥
        String key = account.getPassword();
        Claims claims = Jwts.parser()
                //设置签名秘钥
                .setSigningKey(key)
                //设置需要解析的JWT
                .parseClaimsJws(token).getBody();
        if (claims.get("password").equals(account.getPassword())) {
            return true;
        }
        return false;
    }

}
